package com.sgy.config;

import com.sgy.utils.SqliteBuilder;
import com.sgy.utils.SqliteUtils;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * @author shenguangyang
 * @date 2022-08-14 7:50
 */
@MapperScan(basePackages = "com.sgy.mapper")
@Configuration
public class SqlLiteConfig {
    //数据源url
    @Value("${spring.datasource.url}")
    private String dataSourceUrl;

    /**
     * 配置sqlite数据源
     * @return
     */
    @PostConstruct
    public void init(){
        // 尝试创建sqlite文件-不存在时创建
        SqliteUtils.initSqliteFile(SqliteUtils.getFilePath(dataSourceUrl));
        // 创建数据源
        DataSource dataSource  = SqliteBuilder.create().url(dataSourceUrl).build();
        try {
            // 尝试初始化数据库-表不存在时创建
            SqliteUtils.initProjectDb(dataSource.getConnection(), SqliteUtils.getDbName(dataSourceUrl));
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
